package de.graffiti.beans;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.ejb.Stateless;
import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import de.graffiti.entities.Content;
import de.graffiti.entities.Wallpaper;
import de.graffiti.interfaces.WallpaperService;

@Stateless
public class WallpaperServiceBean implements WallpaperService
{

	@PersistenceContext(unitName = "graffiti")
	private EntityManager em;

	/**
	 * 
	 */
	public de.graffiti.interfaces.Wallpaper getWallpaper(int id)
	{
		if (em != null)
		{
			Query query = em.createNamedQuery("Wallpaper.findById");
			query.setParameter("wallpaperid", id);
			if (query.getResultList().size() > 0)
			{
				Wallpaper entity = (Wallpaper) query.getResultList().get(0);
				// WallpaperVO wallpaper = new WallpaperVO(
				// entity.getAuthor(), entity.getPaintedcontent(),
				// entity.getOriginalcontent(), entity.getContenttype(),
				// entity.getCreationdate(),
				// entity.getRepeating(), entity.getStatus(),
				// entity.getHeight(), entity.getWidth());
				return entity;
			}
		}
		return null;

	}

	/**
	 * 
	 */
	public Vector<de.graffiti.interfaces.Wallpaper> getAll()
	{
		Vector<de.graffiti.interfaces.Wallpaper> result = new Vector<de.graffiti.interfaces.Wallpaper>();
		try
		{
			Query query = em.createNamedQuery("Wallpaper.getAll");
			query.setParameter("status", "a");
			List resultList = query.getResultList();
			Iterator iter = resultList.iterator();
			while (iter.hasNext())
				result.add((Wallpaper) iter.next());
		}
		catch (NullPointerException e)
		{

		}

		return result;
	}

	/**
	 * 
 	*/
	public Content getContent(int contentid)
	{

		if (em != null)
		{
			Query query = em.createNamedQuery("Content.findById");
			query.setParameter("contentid", contentid);
			if (query.getResultList().size() > 0)
			{
				Content con = (Content) query.getResultList().get(0);
				return con;
			}

		}
		return null;
	}

	/**
	 * 
	 */
	public boolean saveWallpaper(String author, String title, byte[] content, String contenttype, boolean repeating, int height, int width)
	{
		Image img = null;
		byte[] background = content;
		String rep;

		try
		{

			img = ImageIO.read(new ByteArrayInputStream(content));

			if (repeating)
			{
				rep = "t";
				background = createBackground(content, width, height);
			}
			else
			{
				rep = "f";
				height = img.getHeight(null);
				width = img.getWidth(null);
			}

			Content con = new Content();
			con.setData(content);
			con.setContenttype(contenttype);
			em.persist(con);
			int originalid = con.getContentid();
			Content con2 = new Content();
			con2.setData(background);

			con2.setContenttype("image/jpg");
			em.persist(con2);
			int paintedid = con2.getContentid();

			Wallpaper wp = new de.graffiti.entities.Wallpaper();
			wp.setAuthor(author);
			wp.setStatus("a");
			wp.setHeight(height);
			wp.setWidth(width);
			wp.setRepeating(rep);
			wp.setOriginalcontentid(originalid);
			wp.setPaintedcontentid(paintedid);
			wp.setTitle(title);
			wp.setCreationdate(new Date());
			em.persist(wp);

		}
		catch (IOException e)
		{
			e.printStackTrace();
			return false;
		}
		return true;

	}

	/**
	 * 
	 * @param background
	 * @param width
	 * @param height
	 * @return
	 */
	public byte[] createBackground(byte[] background, int width, int height)
	{

		ByteArrayOutputStream os = null;

		try
		{
			BufferedImage img = ImageIO.read(new ByteArrayInputStream(background));
			BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

			Graphics graphics = bufferedImage.createGraphics();
			graphics.drawImage(img, 0, 0, null);
			for (int hor = 0; hor < width / img.getWidth(null) + 1; hor++)
			{
				for (int ver = 0; ver < height / img.getHeight(null) + 1; ver++)
				{
					graphics.drawImage(img, hor * img.getWidth(null), ver * img.getHeight(null), null);
				}
			}

			os = new ByteArrayOutputStream();

			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
			encoder.setJPEGEncodeParam(param);

			encoder.encode(bufferedImage);
		}
		catch (ImageFormatException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return os.toByteArray();
	}

}
